﻿// Learn more about F# at http://fsharp.net

module ImageFetcher

open System
open System.IO
open System.Net
open System.Xml.Linq
open Microsoft.FSharp.Control.WebExtensions

let xrs = new System.Xml.XmlReaderSettings()
xrs.CheckCharacters <- false

let getImageAsync(id:int) =
    async { 
        try
            let uri = new System.Uri(String.Format("http://api.renjian.com/statuses/show/{0}.xml", id))
            let webClient = new WebClient()
            webClient.Encoding <- System.Text.Encoding.UTF8;
            let! xmlText = webClient.AsyncDownloadString(uri)
            webClient.Dispose()
            try
                return XElement.Parse(xmlText);
            with
                | :? System.Xml.XmlException -> 
                    let xr = System.Xml.XmlReader.Create(new StringReader(xmlText), xrs)
                    return XElement.Load(xr)
        with
            | ex -> return null
    }

let elementFilter(x:XElement) =
    if x = null then false
    elif x.Element(XName.Get("status_type")).Value = "PICTURE" && x.Element(XName.Get("original_url")) <> null && x.Element(XName.Get("thumbnail")) <> null then true
    else false

let GetMoreImages startID num =
    [for x in 1..num -> startID - x]
    |> Seq.map getImageAsync
    |> Async.Parallel
    |> Async.StartAsTask
    |> fun task -> task.Result
    |> Seq.filter elementFilter